package main

import (
	"sync"
)

type ScriptManager struct {
	maxConcurrent int
	wg            sync.WaitGroup
	mu            sync.Mutex
	running       int
	executors     map[string]*Executor // 新增：管理所有脚本
}

func NewScriptManager(maxConcurrent int) *ScriptManager {
	return &ScriptManager{
		maxConcurrent: maxConcurrent,
		executors:     make(map[string]*Executor),
	}
}

func (sm *ScriptManager) RunScript(script string) {
	sm.mu.Lock()
	if sm.running >= sm.maxConcurrent {
		sm.mu.Unlock()
		return
	}
	if _, exists := sm.executors[script]; exists {
		sm.mu.Unlock()
		return // 已经在运行
	}
	sm.running++
	sm.wg.Add(1)
	executor := NewExecutor(script, &sm.wg)
	sm.executors[script] = executor
	sm.mu.Unlock()

	go func() {
		executor.Run()
		sm.mu.Lock()
		delete(sm.executors, script)
		sm.running--
		sm.mu.Unlock()
	}()
}

func (sm *ScriptManager) StopScript(script string) {
	sm.mu.Lock()
	executor, exists := sm.executors[script]
	sm.mu.Unlock()
	if exists {
		executor.Stop()
	}
}

func (sm *ScriptManager) KillScript(script string) {
	sm.mu.Lock()
	executor, exists := sm.executors[script]
	sm.mu.Unlock()
	if exists {
		executor.Kill()
	}
}

func (sm *ScriptManager) ListScripts() []string {
	sm.mu.Lock()
	defer sm.mu.Unlock()
	scripts := make([]string, 0, len(sm.executors))
	for script := range sm.executors {
		scripts = append(scripts, script)
	}
	return scripts
}

func (sm *ScriptManager) Wait() {
	sm.wg.Wait()
}
